import React from 'react'
    
export default function Cart() {
  const [list,setList]= React.useState( [{ selected: true, name: "苹果", price: 10, num: 1, id: 0 },
  { selected: false, name: "香蕉", price: 2, num: 1, id: 1 },
  { selected: false, name: "西红柿", price: 11, num: 3, id: 2 },]
        )
function changeSeleted(index){
    list[index].selected=!list[index].selected

    setList([...list])
}
function changeNum(index,n){
    list[index].num+=n
    setList([...list])
}
function del(index){
    list.splice(index,1)
    setList([...list])
}
const total=  React.useMemo(()=>{
    
        let count=0
        list.filter(m=>m.selected).forEach(n=>{
          count+=n.price*n.num
        })
        return count
       
},[list])
  return (
    <div>
            <table>
                    <thead>
                        <tr>
                             <th><input type="checkbox" /></th>
                                <th>商品名</th>
                                <th>单价</th>
                                <th>数量</th>
                                <th>小计</th>
                                <th>操作</th>
                        </tr>
                    </thead>
                <tbody>
                {list.map((item,index)=>{
                return <tr key={item.id}>
                    <td><input onChange={()=>changeSeleted(index)} checked={item.selected} type="checkbox" /></td>
                    <td>{item.name}</td>
                    <td>{item.price}</td>
                    <td><button disabled={item.num==1} onClick={()=>changeNum(index,-1)}>-</button>{item.num}<button onClick={()=>changeNum(index,1)}>+</button></td>
                    <td>{item.num*item.price}</td>
                    <td><button onClick={()=>del(index)}>删除</button></td>


                </tr>


             })} 


                 </tbody>
                <tfoot>
                    <tr><td>总计:{total}</td></tr>
                </tfoot>
            </table>


    </div>
  )
}
